/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ReceiptChannelActivity.java
 *   @Date: 19-2-1 上午10:09
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.bean.ImageInfo;
import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.adapter.OtcReceiptChannelAdapter;
import io.bhex.app.otc.listener.AdapterItemClickListener;
import io.bhex.app.otc.presenter.ReceiptChannelPresenter;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.otc.OtcPayChannelApi;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcPayChannelListResponse;
import io.bhex.sdk.otc.bean.OtcPaymentChannelBean;

/**
 * 收款方式
 */
public class ReceiptChannelActivity extends BaseActivity<ReceiptChannelPresenter,ReceiptChannelPresenter.ReceiptChannelUI> implements ReceiptChannelPresenter.ReceiptChannelUI {
    private SmartRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private OtcReceiptChannelAdapter adapter;
    private TopBar topBar;
    private List<OtcPaymentChannelBean> receiptChannelList;
    private OtcPayChannelListResponse currentReceiptChannelListResponse;
    private View emptyView;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_receipt_channel_layout;
    }

    @Override
    protected ReceiptChannelPresenter createPresenter() {
        return new ReceiptChannelPresenter();
    }

    @Override
    protected ReceiptChannelPresenter.ReceiptChannelUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightImg(CommonUtil.isBlackMode()?R.mipmap.icon_add_night:R.mipmap.icon_add);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentReceiptChannelListResponse != null) {
//                    if (receiptChannelList != null) {
//                        if (receiptChannelList.size()<3) {
//                            IntentUtils.goAddReceiptChannel(ReceiptChannelActivity.this,currentReceiptChannelListResponse,null);
//                        }else{
//                            ToastUtils.showShort(getString(R.string.string_otc_receipt_channle_up_to_three));
//                        }
//                    }else{
                        IntentUtils.goAddReceiptChannel(ReceiptChannelActivity.this,currentReceiptChannelListResponse,null);
//                    }
                }

            }
        });
        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        emptyView = layoutInflater.inflate(R.layout.empty_layout, swipeRefresh, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(200);
        emptyView.setLayoutParams(layoutParams);
        recyclerView = viewFinder.find(R.id.recyclerView);
    }

    @Override
    public void showReceiptChannel(final OtcPayChannelListResponse response) {
        currentReceiptChannelListResponse = response;
        receiptChannelList = response.getArray();
        if (receiptChannelList != null) {
            if (adapter == null) {
                adapter = new OtcReceiptChannelAdapter(this,receiptChannelList,bankMap, new AdapterItemClickListener(){
                    @Override
                    public void onClick(View view, Object oc) {
                    }
                });
                adapter.isFirstOnly(false);
                adapter.setEnableLoadMore(false);
                adapter.setEmptyView(emptyView);

                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter mAdapter, View view, int position) {
                        List<OtcPaymentChannelBean> data = mAdapter.getData();
                        if (data != null) {

                            final OtcPaymentChannelBean item = data.get(position);
                            switch (view.getId()){
                                case R.id.itemView:
                                    IntentUtils.goAddReceiptChannel(ReceiptChannelActivity.this,currentReceiptChannelListResponse,item);
                                    break;
                                case R.id.qrcode:
                                    String qrcodeUrl = item.getQrcode();
                                    if (!TextUtils.isEmpty(qrcodeUrl)) {
                                        if (qrcodeUrl.startsWith("/")) {
                                            qrcodeUrl = qrcodeUrl.replaceFirst("/", "");
                                        }
                                        qrcodeUrl = UrlsConfig.API_OTC_URL + qrcodeUrl;
                                    }
                                    List<String> urls = new ArrayList<>();
                                    urls.add(qrcodeUrl);
                                    showPicBrowser(0,urls);
                                    break;
                                case R.id.item_delete:
                                    DialogUtils.showTradePasswdDialog(ReceiptChannelActivity.this, ReceiptChannelActivity.this.getResources().getString(R.string.string_finance_passwd), "", "", true, new DialogUtils.OnOtcEventListener() {
                                        @Override
                                        public void onConfirm(String editContent) {
                                            adapter.closeOpenedSwipeItemLayoutWithAnim();
                                            getPresenter().deletePayChannel(item,editContent);
                                        }

                                        @Override
                                        public void onCancel() {

                                        }
                                    });
                                    break;
                                case R.id.toggleButton:
                                    OtcPayChannelApi.switchPayWay(item.getId(),item.getVisible()==0?1:0,new SimpleResponseListener<ResultResponse>(){
                                        @Override
                                        public void onFinish() {
                                            super.onFinish();
                                        }

                                        @Override
                                        public void onSuccess(ResultResponse response) {
                                            super.onSuccess(response);
                                            if (CodeUtils.isSuccess(response,true)) {
                                                if (response.isSuccess()) {
                                                    ToastUtils.showShort(ReceiptChannelActivity.this.getResources().getString(R.string.string_set_success));
                                                    item.setVisible(item.getVisible()==0?1:0);
                                                    adapter.notifyDataSetChanged();
                                                    return;
                                                }
                                                ToastUtils.showShort(ReceiptChannelActivity.this.getResources().getString(R.string.string_set_failed));
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable error) {
                                            super.onError(error);
                                        }
                                    });
                                    break;
                            }
                        }
                    }
                });
                recyclerView.setAdapter(adapter);
            } else {
                adapter.setNewData(receiptChannelList);
            }
        }
    }

    private HashMap<String,OtcConfigResponse.BankBean> bankMap = new HashMap<>();
    @Override
    public void showBankList(List<OtcConfigResponse.BankBean> bankList) {
        if (bankList != null) {
            bankMap.clear();
            for (OtcConfigResponse.BankBean bankBean : bankList) {
                bankMap.put(bankBean.getBankId(),bankBean);
            }
        }
    }

    /**
     *预览图片
     */
    private void showPicBrowser(int index, List<String> imgUrls) {

        if(imgUrls == null || index >= imgUrls.size())
            return;

        ArrayList<ImageInfo> imageInfoList = new ArrayList<>();
        ImageInfo imageInfo;
        for (String imgUrl : imgUrls) {
            imageInfo = new ImageInfo();
            // 原图地址（必填）
            imageInfo.setOriginUrl(imgUrl);
            // 缩略图地址（必填）
            // 如果没有缩略图url，可以将两项设置为一样。（注意：此处作为演示用，加了-1200，你们不要这么做）
//            imageInfo.setThumbnailUrl(image.concat("-1200"));
            imageInfo.setThumbnailUrl(imgUrl);
            imageInfoList.add(imageInfo);
            imageInfo = null;
        }

        ImagePreview.getInstance()
                .setContext(this)
                .setIndex(index)
                .setImageInfoList(imageInfoList)
                .setShowDownButton(true)
                //.setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                .setFolderName("BhexImage")
                .setScaleLevel(1, 3, 5)
                .setZoomTransitionDuration(300)

                .setEnableClickClose(true)// 是否启用点击图片关闭。默认启用
                .setEnableDragClose(true)// 是否启用上拉/下拉关闭。默认不启用

                .setShowCloseButton(true)// 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setCloseIconResId(R.drawable.ic_action_close)// 设置关闭按钮图片资源，可不填，默认为：R.drawable.ic_action_close

                .setShowDownButton(true)// 是否显示下载按钮，在页面右下角。默认显示
                .setDownIconResId(R.drawable.icon_download_new)// 设置下载按钮图片资源，可不填，默认为：R.drawable.icon_download_new

                .setShowIndicator(true)// 设置是否显示顶部的指示器（1/9）。默认显示
                .start();
    }
}
